<?php
namespace x;
use x\my\Jump;

class App {
	public $version = '0.0.1';
	public $debug = true;
	public $pathinfo = null;
	public $config = [];
	public $m = 'index';
	public $c = 'index';
	public $a = 'init';
	public $container;
	/**
	 * 执行应用程序
	 * @access public
	 */
	public function run() {
		$this->config();
		$this->route();
		$this->autoload();
		$this->container = Container::getInstance();
		$this->controller();
	}
	/**
	 * 实例化控制器
	 * 执行程序
	 */
	public function controller() {
		if ($this->c == 'jump') {
			$this->a == 'success' ? Jump::success() : Jump::error();
			return;
		}
		$className = 'app\\' . strtolower($this->m) . '\\controller\\' . ucwords($this->c);
		$class = $this->container->make($className);
		$action = ucwords($this->a);
		$vars = [];
		return $this->container->invokeMethod([$class, $action], $vars);
	}

	/**
	 * 引入model文件
	 * @return [type] [description]
	 */
	public function model($name, $layer = '', $vars = []) {
		switch ($layer) {
		case '':
			$class = 'app\\' . $this->m . '\\model\\' . ucfirst($name);
			break;
		case 'c':
			$class = 'app\\common\\model\\' . ucfirst($name);
			break;
		case 'xcom':
			$class = 'xcom\\model\\' . ucfirst($name);
			break;
		default:
			$class = 'x\\' . $layer . '\\model\\' . ucfirst($name);
			break;
		}
		return Container::get($class, $vars);
	}

	/**
	 * 引入server文件
	 * @return [type] [description]
	 */
	public function server($name, $layer = '', $vars = []) {
		switch ($layer) {
		case '':
			$class = 'app\\' . $this->m . '\\server\\' . ucfirst($name);
			break;
		case 'c':
			$class = 'app\\common\\server\\' . ucfirst($name);
			break;
		case 'xcom':
			$class = 'xcom\\server\\' . ucfirst($name);
			break;
		default:
			$class = 'x\\' . $layer . '\\server\\' . ucfirst($name);
			break;
		}
		return Container::get($class, $vars);
	}

	//加载配置
	public function config() {
		$this->debug = env('debug');

		if (!$this->debug) {
			ini_set('display_errors', 'Off');
		} elseif (PHP_SAPI != 'cli') {
			//重新申请一块比较大的buffer
			if (ob_get_level() > 0) {
				$output = ob_get_clean();
			}
			ob_start();
			if (!empty($output)) {
				echo $output;
			}
		}
		// 设置系统时区
		date_default_timezone_set(env('default_timezone'));
	}

	//设置路由
	public function route() {
		$this->pathinfo();
		$arr = array_merge(array_filter(explode("/", $this->pathinfo)), []);

		if (G::$web_site_id) {
			if (isset($arr[0])) {
				$this->m = strtolower($arr[0]);
			}

			if (isset($arr[1])) {
				$this->c = strtolower($arr[1]);
			}

			if (isset($arr[2])) {
				$this->a = strtolower($arr[2]);
			}

		} else {
			$domain = env('domain');
			!isset($domain[strtolower($_SERVER['HTTP_HOST'])]) && exit($_SERVER['HTTP_HOST'] . " is not configured");
			$this->m = strtolower($domain[strtolower($_SERVER['HTTP_HOST'])]);
			if (isset($arr[0])) {
				$this->c = strtolower($arr[0]);
			}

			if (isset($arr[1])) {
				$this->a = strtolower($arr[1]);
			}

		}
		G::$m = $this->m;
		$this->a = str_ireplace(['.', 'html', 'php', 'htmls', 'html'], '', $this->a);
		//t([$arr, $this->m,$this->c,$this->a]);
	}

	//自动加载文件
	public function autoload() {
		$dir = APP_PATH . 'autoload';
		if (false != ($handle = opendir($dir))) {
			while (false !== ($file = readdir($handle))) {
				if ($file != "." && $file != ".." && strpos($file, ".")) {
					include_once APP_PATH . 'autoload/' . $file;
				}
			}
			closedir($handle);
		}
	}

	/**
	 * 获取当前请求URL的pathinfo信息（含URL后缀）
	 * @access public
	 * @return string
	 */
	public function pathinfo() {
		if (is_null($this->pathinfo)) {
			if (isCli()) {
				// CLI模式下 index.php module/controller/action/params/...
				$_SERVER['PATH_INFO'] = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : '';
			}
			// 分析PATHINFO信息
			if (!isset($_SERVER['PATH_INFO'])) {
				foreach (['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REQUEST_URI'] as $type) {
					if (!empty($_SERVER[$type])) {
						if (0 === strpos($_SERVER[$type], $_SERVER['SCRIPT_NAME'])) {
							$_SERVER['PATH_INFO'] = substr($_SERVER[$type], strlen($_SERVER['SCRIPT_NAME']));
						} else {
							$_SERVER['PATH_INFO'] = $_SERVER[$type];
						}
						break;
					}
				}
			}
			//首页403问题
			if (!isset($_SERVER['PATH_INFO']) or $_SERVER['PATH_INFO'] == '403.html') {
				$_SERVER['PATH_INFO'] = '/';
			}
			$_SERVER['PATH_INFO'] = str_replace(['/index.php'], '', $_SERVER['PATH_INFO']);
			$this->pathinfo = empty($_SERVER['PATH_INFO']) ? '/' : ltrim($_SERVER['PATH_INFO'], '/');
			$this->pathinfo = preg_replace("/([\s\S]*)([\?]+)([\s\S]*)/", "$1", $this->pathinfo);
			$this->pathinfo = preg_replace("/([\s\S]*)([\.]+)([\s\S]*)/", "$1", $this->pathinfo);
			$this->pathinfo = preg_replace("/([\s\S]*)([\#]+)([\s\S]*)/", "$1", $this->pathinfo);
		}
		return $this->pathinfo;
	}
}
